<template>
  <div class="app-container">
    <el-form :inline="true" :model="query" size="mini">
      <el-form-item label="角色名称：">
        <el-input v-model.trim="query.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" type="primary" @click="queryData">查询</el-button>
        <el-button icon="el-icon-refresh" @click="reload">重置</el-button>
        <el-button v-if="!roleIds" icon="el-icon-circle-plus-outline" type="primary" @click="openAdd">新增</el-button>

        <el-button v-if="roleIds" icon="el-icon-circle-plus-outline" type="success" @click="handleUserRole">设置角色</el-button>
      </el-form-item>
    </el-form>
    <!-- 数据列表 :data 绑定渲染的数据, border 纵向边框 -->
    <el-table @selection-change="handleSelectChange" row-key="id" ref="dataTable" :data="list" border highlight-current-row style="width: 100%">
      <el-table-column v-if="roleIds" type="selection" reserve-selection align="center" width="60"></el-table-column>
      <!-- type="index"获取索引值，从1开始 ，label显示标题，prop 数据字段名，width列宽 -->
      <el-table-column align="center" type="index" label="序号" width="60"></el-table-column>
      <el-table-column align="center" prop="name" label="角色名称"></el-table-column>
      <el-table-column align="center" prop="remark" label="备注"></el-table-column>
      <el-table-column align="center" label="操作" v-if="!roleIds">
        <template slot-scope="scope">
          <el-button @click="handlePermission(scope.row.id)" size="mini" type="success">分配权限</el-button>
          <el-button @click="handleEdit(scope.row.id)" size="mini">编辑</el-button>
          <el-button @click="handleDelete(scope.row.id)" size="mini" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page.current"
      :page-sizes="[10, 20, 50]"
      :page-size="page.size"
      :total="page.total"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <edit :title="edit.title" :visible="edit.visible" :formData="edit.formData" :remoteClose="remoteClose"></edit>

    <permission title="分配权限" :visible="per.visible" :remotePerClose="remotePerClose" :roleId="per.roleId" />
  </div>
</template>

<script>
import api from '@/api/role';
import Edit from './edit';
import Permission from './permission';
export default {
  components: { Edit, Permission },
  props: {
    roleIds: null
  },
  data() {
    return {
      checkedRoleList:[],
      list: [],
      page: {
        total: 0,
        current: 1,
        size: 20
      },
      query: {},
      edit: {
        // 子组件中引用
        title: '',
        visible: false,
        formData: {}
      },
      per: {
        roleId: null,
        visible: false
      }
    };
  },
  created() {
    this.fetchData();
  },
  watch: {
    roleIds() {
      this.query = {};
      this.queryData();
    }
  },
  methods: {
    handleSelectChange(val){
      this.checkedRoleList = val
    },
    //关闭分配权限弹窗
    remotePerClose() {
      this.per.visible = false;
      this.per.roleId = null;
      this.fetchData();
    },
    remoteClose() {
      this.edit.formData = {};
      this.edit.visible = false;
      this.fetchData();
    },
    reload() {
      this.query = {};
      this.fetchData();
    },
    // 新增方法
    openAdd() {
      this.edit.visible = true;
      this.edit.title = '新增';
    },
    handleUserRole() {
      console.log('设置角色');
      const checkedRoleIds = [];
      this.checkedRoleList.forEach(item =>{
        checkedRoleIds.push(item.id)
      })
      this.$emit('saveUserRole',checkedRoleIds)
    },
    queryData() {
      // 将页码变为第1页
      this.page.current = 1;
      this.fetchData();
    },
    // 当每页显示条数改变后,被触发 , val是最新的每页显示条数
    handleSizeChange(val) {
      this.page.size = val;
      this.fetchData();
    },
    // 当页码改变后,被触发 , val 是最新的页面
    handleCurrentChange(val) {
      this.page.current = val;
      this.fetchData();
    },
    handlePermission(id) {
      //console.log('分配权限', id);
      this.per.visible = true;
      this.per.roleId = id;
    },
    handleEdit(id) {
      console.log('编辑', id);
      api.getById(id).then((response) => {
        if (response.code === 20000) {
          this.edit.formData = response.data;
        }
        this.edit.title = '编辑';
        this.edit.visible = true;
      });
    },
    handleDelete(id) {
      console.log('删除', id);
      this.$confirm('确定删除这条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          api.deleteById(id).then((response) => {
            this.$message({
              type: response.code === 20000 ? 'success' : 'error',
              message: response.message
            });
            this.fetchData();
          });
        })
        .catch(() => {});
    },
    fetchData() {
      api.getList(this.query, this.page.current, this.page.size).then((response) => {
        this.list = response.data.records;
        this.page.total = response.data.total;
        // 列表有数据后，勾选用户角色 +++++
        this.checkedRoles();
      });
    },
    // 勾选用户角色 +++++
    checkedRoles() {
      // 清空上一次的选择
      this.$refs.dataTable.clearSelection();
      if (this.roleIds) {
        // 取出列表中每个角色，与用户角色ids进行匹配，匹配上了则选中
        this.list.forEach((item) => {
          // 匹配上了
          if (this.roleIds.indexOf(item.id) !== -1) {
            // 选中，注意在 el-table 加上 ref="dataTable"
            this.$refs.dataTable.toggleRowSelection(item, true);
          }
        });
      }
    }
  }
};
</script>

<style></style>
